use std::fs;
use std::path::{Path, PathBuf};
use image::DynamicImage;
use regex::Regex;
use walkdir::WalkDir;
use crate::error::Res;

pub fn change_extension<P: AsRef<Path>>(path: P, new_extension: &str) -> PathBuf {
    let mut new_path = path.as_ref().to_path_buf();
    new_path.set_extension(new_extension);
    new_path
}

pub fn collect_images<P: AsRef<Path>>(source_path: P, image_name_pattern: &str) -> Res<Vec<Image>> {
    let mut images = Vec::<Image>::new();
    let reg = Regex::new(image_name_pattern)?;
    for entry in WalkDir::new(source_path) {
        let entry = entry.unwrap();
        if entry.file_type().is_file() {
            let file_name = entry.file_name().to_string_lossy().to_string();
            if reg.is_match(&file_name) {
                let image_path = entry.path();
                let image = fs::read(image_path).unwrap();
                if let Err(_) = image::guess_format(&image) {
                    continue;
                }
                let img = image::load_from_memory(&image).unwrap();
                let w = img.width();
                let h = img.height();
                images.push(Image {
                    name: file_name,
                    buffer: img,
                    rect: Rect { x: 0, y: 0, w, h },
                });
            }
        }
    }
    Ok(images)
}

pub struct Image {
    pub name: String,
    pub buffer: DynamicImage,
    pub rect: Rect,
}

#[derive(Debug)]
pub struct Rect {
    pub x: u32,
    pub y: u32,
    pub w: u32,
    pub h: u32,
}


